package com.saber.thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 *
 * @author
 *
 */
public class SharedThreadPoolExecutorHolder {

	/**
	 * 共享线程池
	 */
	public transient static final SharedThreadPoolExecutor sharedThreadPoolExecutor;

	/**
	 * 任务队列
	 */
	public transient static BlockingQueue<Runnable> pendingRequests = null;

	/**
	 * 核心线程
	 */
	private transient static Thread[] schedulers = null;

	/**
	 * 初期化处理
	 */
	static {
		sharedThreadPoolExecutor = new SharedThreadPoolExecutor();
		// 设定核心线程池大小
		sharedThreadPoolExecutor.setCoreSize(32);
		// 设定最大池大小
		sharedThreadPoolExecutor.setMaxSize(1024);
		// 设定超过核心池大小的线程可以在终止前保持空闲的时间值。
		sharedThreadPoolExecutor.setKeepAliveTime(60);
		// 设定队列存放任务数目的最大值
		sharedThreadPoolExecutor.setWorkQueueCapacity(1024);

		sharedThreadPoolExecutor.initialize();

		// 无界队列
		pendingRequests = new LinkedBlockingQueue<Runnable>();

		// 开启核心线程32个block住等待调用
		int threadCount = 32;
		schedulers = new Thread[threadCount];
		for (int i = 0; i < threadCount; i++) {
			schedulers[i++] = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Runnable runnable = pendingRequests.take();
						runnable.run();
					} catch (Throwable x) {
						x.printStackTrace();
					}
				}
			});
			schedulers[i - 1].start();
		}
	}
}
